import os
import sys
import re
import urllib
from datetime import datetime
from mimetypes import types_map
import logging

import webapp2
from google.appengine.ext.webapp import template
from google.appengine.api import urlfetch
from google.appengine.api import users
from google.appengine.ext import db

sys.path = [os.path.dirname(__file__)] + sys.path

import AppEnv
import base.RequestHandler
import base.Role
import base.Error
import base.Decorators
import models.AppConfig
import models.Blog
import models.Comment
import models.Post
import models.Tag
import models.Theme
import models.TrackBack
import utils

class InitApp(webapp2.RequestHandler):
    @base.Decorators.needRole(base.Role.Admin)
    def get(self):
        path = os.path.join(AppEnv.app_root, 'template', 'default', models.Theme.AppInit_page)
        self.response.out.write(template.render(path, []))
        return 

    @base.Decorators.needRole(base.Role.Admin)
    def post(self):
        try:
            utils.deleteAllModels(models.AppConfig.AppConfig,
                                  models.Blog.Blog,
                                  models.Comment.Comment,
                                  models.Post.Post,
                                  models.Tag.Tag,
                                  models.Theme.Theme,
                                  models.TrackBack.TrackBack)
            # delete all appconfig
            # utils.deleteAllModels(models.AppConfig.AppConfig)
            # Reset AppConfig
            appconfig = models.AppConfig.AppConfig()
            appconfig.put()

            # delete all theme
            # utils.deleteAllModels(models.Theme.Theme)
            # default theme
            #models.Theme.create('default')
            logging.error("OK")
            models.Theme.initAllThemes()

            msg = 'Application initilized!'
            succeed = True
        except Exception,e:
            raise e
            msg = str(e)
            succeed = False
        
        path = os.path.join(AppEnv.app_root, 'template', 'default', models.Theme.AppInit_page)
        self.response.out.write(template.render(path, {'msg': msg,'succeed': succeed}))
        return

    def handle_exception(self, exception, debug_mode):
        if isinstance(exception, base.Error.NoPrivilegeError):
            self.redirect(users.create_logout_url(users.create_login_url(urllib.unquote_plus(self.request.uri))))
            return
        return webapp2.RequestHandler.handle_exception(self, exception, debug_mode)

class AdminThemes(base.RequestHandler.PageRequestHandler):
    @base.Decorators.needRole(base.Role.Admin)
    def get(self):
        themelist = models.Theme.getAllThemes()
        self.templatedic['themelist'] = themelist
        self.templatedic['themeAvailable'] = models.Theme.getAvailableThemes()
        self.render(models.Theme.AdminThemes_page, True)
        return

class AdminBlogger(base.RequestHandler.PageRequestHandler):
    @base.Decorators.needRole(base.Role.Admin)
    def get(self):
        pass
    @base.Decorators.needRole(base.Role.Admin)
    def post(self):
        pass

class AdminApp(base.RequestHandler.PageRequestHandler):
    @base.Decorators.needRole(base.Role.Admin)
    def get(self):
        bloglist = models.Blog.Blog.all().order('blogId').fetch(limit=1000)
        self.templatedic['bloglist'] = bloglist
        self.templatedic['extraPath'] = 'Admin'
        self.render(models.Theme.AdminApp_page, True)
        return

    @base.Decorators.needRole(base.Role.Admin)
    def post(self):
        pass

app = webapp2.WSGIApplication([
    (AppEnv.apppath + '/admin/init', InitApp),
    (AppEnv.apppath + '/admin/themes', AdminThemes),
    (AppEnv.apppath + '/admin/.+', AdminBlogger),
    (AppEnv.apppath + '/admin/?', AdminApp ),
    ('.*', base.RequestHandler.HTTP404),
], debug=AppEnv.debug)

